package com.example.securitydemo.authentication;

import com.example.securitydemo.entities.Permission;
import com.example.securitydemo.entities.User;
import com.example.securitydemo.services.IPermissionService;
import com.example.securitydemo.services.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    IUserService userService;
    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.findByName(s);
        if (user != null) {
            List<Permission> permissions = permissionService.findUserPermissionsByUserId(user.getId());
            Set<GrantedAuthority> authorities = new HashSet<>();
            for (Permission p : permissions) {
                if (p != null && StringUtils.isNoneEmpty(p.getPermissionName())) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + p.getPerms().toUpperCase());
                    authorities.add(grantedAuthority);
                }
            }
            return new MyUserDetails(user, authorities);
        } else {
            throw new UsernameNotFoundException("user: " + s + " do not exist!");
        }
    }
}
